//
//  XinDataHelper.swift
//  XinGuoSearch
//
//  Created by 李东 on 2024/3/23.
//

import UIKit
import HandyJSON
class XinDataHelper: NSObject {

    static let shared = XinDataHelper()
    let LocalKey = "mydataKey"
    lazy var array = [XinCoffeeModel]()
    



    
    func getLocalList() -> [XinCoffeeModel] {
        if !array.isEmpty {
            return array
        }
        if let tt = UserDefaults.standard.object(forKey: LocalKey) as? String {
            if let list = [XinCoffeeModel].deserialize(from: tt) as? [XinCoffeeModel] {
                array = list.sorted(by: { m1, m2 in
                    m1.ts > m2.ts
                })
            }
        }
        return array
    }
    
    func addData(model: XinCoffeeModel)  {
        if array.contains(where: {$0.ymd == model.ymd}) {
            if let ii = array.firstIndex(where: {$0.ymd == model.ymd}) {
                let m1 = array[ii]
                m1.count += 1
                m1.mg += model.mg
                m1.coffee = model.coffee
                m1.time = model.time
                m1.ts = model.ts
                array[ii] = m1
            }
        }else {
//            array.append(model)
            array.insert(model, at: 0)
        }
        if let json = array.toJSONString() {
            UserDefaults.standard.set(json, forKey: LocalKey)
            UserDefaults.standard.synchronize()
        }
    }
}
